<template>
  <div>
    <el-upload
      ref="upload"
      :action="actionUrl"
      :show-file-list="false"
      :http-request="uploadFile">
      <el-button size="small" type="primary">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  /* eslint-disable vue/require-prop-types */
  props: ['idx'],
  data() {
    return {
      actionUrl: '',
      imageUrl: '',
      fileList: []
    }
  },
  created() {
    this.initUploadFileurl()
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
    },
    initUploadFileurl() {
      this.actionUrl = process.env.BASE_API + 'file/uploadImageAndCrtThumbImagesRichEdit'
    },
    uploadFile(content) {
      const fd = new FormData()
      fd.append('images', content.file)
      fd.append('resPath', this.resPath)

      const fileSize = fd.size / 1024 / 1024
      if (fileSize > 2) {
        this.$message({
          message: '上传图片不能大于2M',
          type: 'warning'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        axios.post(content.action, fd).then(res => {
          loading.close()
          if (res.data.code === 1) {
            const obj = {
              imgurl: res.data.data[0].maxImageUrl,
              index: this.idx
            }
            this.$emit('emitSuccessImg', obj)
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            })
          }
        })
      }
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
</style>
